const mongoose = require("mongoose");

const TaskSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
      trim: true,
      maxlength: 200,
    },
    description: {
      type: String,
      trim: true,
      maxlength: 2000,
      default: "",
    },
    group: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Group",
      required: true,
    },
    creator: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    assignee: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      default: null,
    },
    status: {
      type: String,
      enum: ["pending", "in_progress", "completed", "cancelled", "on_hold"],
      default: "pending",
    },
    priority: {
      type: String,
      enum: ["low", "medium", "high", "urgent"],
      default: "medium",
    },
    dueDate: {
      type: Date,
      default: null,
    },
    completedAt: {
      type: Date,
      default: null,
    },
    tags: {
      type: [String],
      default: [],
    },
    attachments: {
      type: [
        new mongoose.Schema(
          {
            filename: { type: String, required: true },
            originalName: { type: String, required: true },
            mimeType: { type: String, required: true },
            size: { type: Number, required: true },
            url: { type: String, required: true },
            uploadedBy: {
              type: mongoose.Schema.Types.ObjectId,
              ref: "User",
              required: true,
            },
          },
          { _id: true }
        ),
      ],
      default: [],
    },
    estimatedHours: {
      type: Number,
      min: 0,
      default: null,
    },
    actualHours: {
      type: Number,
      min: 0,
      default: null,
    },
    // 任务依赖关系
    dependencies: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "Task",
      default: [],
    },
    // 子任务
    parentTask: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Task",
      default: null,
    },
    // 任务进度百分比
    progress: {
      type: Number,
      min: 0,
      max: 100,
      default: 0,
    },
  },
  { timestamps: true }
);

// 索引优化
TaskSchema.index({ group: 1, status: 1 });
TaskSchema.index({ assignee: 1, status: 1 });
TaskSchema.index({ creator: 1 });
TaskSchema.index({ dueDate: 1 });
TaskSchema.index({ group: 1, dueDate: 1 });

// 虚拟字段：是否已过期
TaskSchema.virtual("isOverdue").get(function () {
  if (
    !this.dueDate ||
    this.status === "completed" ||
    this.status === "cancelled"
  ) {
    return false;
  }
  return new Date() > this.dueDate;
});

// 虚拟字段：剩余天数
TaskSchema.virtual("daysRemaining").get(function () {
  if (
    !this.dueDate ||
    this.status === "completed" ||
    this.status === "cancelled"
  ) {
    return null;
  }
  const now = new Date();
  const diffTime = this.dueDate - now;
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
});

// 确保虚拟字段在JSON序列化时包含
TaskSchema.set("toJSON", { virtuals: true });

const Task = mongoose.model("Task", TaskSchema);

module.exports = Task;
